import json
import os
import sys
import requests
from pyquery import PyQuery as pq

def formatContent(html, isRemoveSrcParams=False,env='dev'):
    with open(sys.path[0] + '/config.json') as file:
        configJson = file.read()
    configList = json.loads(configJson)
    formatUrl = configList[env]['formatUrl']
    if isRemoveSrcParams:
        html = removeSrcParams(pq(html)).html()
    data = json.dumps({'content': html})
    response = requests.post(url=formatUrl, data=data)

    result = json.loads(response.text)
    return result['data']['content']


def removeSrcParams(doc):
    global newSrc
    for image in doc('img'):
        if doc(image).attr('src'):
            oldSrc = doc(image).attr('src')
            if oldSrc.find('?') >= 0:
                newSrc = oldSrc[:oldSrc.find('?')]
            else:
                newSrc = oldSrc
        elif doc(image).attr('data-src'):
            oldSrc = doc(image).attr('data-src')
            if oldSrc.find('?') >= 0:
                newSrc = oldSrc[:oldSrc.find('?')]
            else:
                newSrc = oldSrc
        elif doc(image).attr('data-original-src'):
            oldSrc = doc(image).attr('data-original-src')
            if oldSrc.find('?') >= 0:
                newSrc = oldSrc[:oldSrc.find('?')]
            else:
                newSrc = oldSrc
        else:
            continue
        if newSrc.find('http') < 0:
            newSrc = 'https:' + newSrc
        doc(image).attr('src', newSrc)
    return doc


def filterAttributes(doc, attributes):
    for attribute in attributes:
        doc.removeAttr(attribute)
    return doc


def filterTag(doc, tags):
    for tagName in tags:
        doc(tagName).remove()
    return doc
